package com.shanghaionstar.user;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.common.CustomLayoutsGroup;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.more.response.HeadImgRes;
import com.onstar.cn.more.response.PersonalInfoResponse;
import com.onstar.cn.weight.BounceScrollView;
import com.onstar.cn.weight.ProgressLayout;
import com.onstar.cn.weight.discover.ItemViewData;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.MoreActivity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.home.life.AlarmManagerUtil;
import com.shanghaionstar.user.iview.IAccountInfoView;
import com.shanghaionstar.user.presenter.AccountInfoPresenter;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.weight.TopLayout;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by 7828wc on 16/6/29.
 * 个人中心界面
 */
public class AccountInfoFragment extends BaseFragment implements IAccountInfoView {
    @FindViewById
    private LinearLayout datas_layout, thirds_layout;
    @FindViewById
    private TopLayout top_layout;
    @FindViewById
    private ProgressLayout progress_layout;
    @FindViewById
    private CircleImageView head_iv;
    @FindViewById
    private RelativeLayout portrait_rl;
    @FindViewById
    private RelativeLayout portrait_img_rl;
    @FindViewById
    private ImageView def_head_iv;
    @FindViewById
    private BounceScrollView bsv;
    private AccountInfoPresenter presenter;
    private MoreActivity parentActivity;
    private String licenseExpireDate = "";
    private ImageLoader imageLoader;
    private OnstarApplication onstarApplication;
    private DisplayImageOptions options;

    ItemViewData addressViewData;

    @Override
    public int getLayoutId() {
        return R.layout.more_account_info;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        btnBackClick(top_layout);
        if (isFirstLoad()) {
            parentActivity = (MoreActivity) getActivity();
            presenter = new AccountInfoPresenter(((MoreActivity) getActivity()).getScheduler());
            presenter.setView(this);
            presenter.start();
            imageLoader = ImageLoader.getInstance();
            onstarApplication = (OnstarApplication) getActivity().getApplicationContext();
            options = OnstarApplication.getOptions(true, false, R.drawable.def_login_head);
            HeadImgRes headImgRes = onstarApplication.getHeadImgRes();
            if (headImgRes != null) {
                loadHead(headImgRes);
            } else {
                presenter.getData();
            }
        }
    }

    private void loadHead(HeadImgRes res) {
        if (res != null && res.getFullUrl() != null) {
            imageLoader.displayImage(res.getFullUrl(), head_iv, options);
        } else {
            //getHeadImg();
            presenter.getData();
        }
    }

    public void showProgress(boolean b) {
        if (b) {
            progress_layout.setVisibility(View.VISIBLE);
        } else {
            progress_layout.setVisibility(View.GONE);
        }
    }


    List<ItemViewData> datas;

    private void showDatas() {
        datas_layout.removeAllViews();

        datas = new ArrayList<>();
        ItemViewData viewData;

    /*    viewData=new ItemViewData();
        viewData.setText(getString(R.string.option_head_img));
        viewData.setClassName(MoreActivity.class.getName());
        viewData.setShowRightArrow(true);
        datas.add(viewData);
*/


        viewData = new ItemViewData();
        viewData.setText(getString(R.string.option_user_name));
        viewData.setRightText(ApplicationUtil.getInstance().getIdpID());
//        viewData.setClassName(MoreActivity.class.getName());
        viewData.setShowRightArrow(false);
        viewData.setFunctionValue(FunctionNameFindId.Personalinfo_Username.getStringValue());
//        Bundle vehicBundle = new Bundle();
//        vehicBundle.putString(FinalConstants.JUMP_FLAG, VehicleInfoFragment.class.getName());
//        viewData.setBundle(vehicBundle);
        datas.add(viewData);

        viewData = new ItemViewData();
        viewData.setText(getString(R.string.option_phone_num));
        viewData.setRightText(CommonUtil.replaceString(parentActivity.getPhoneNumber(), false));
        viewData.setClassName(MoreActivity.class.getName());
        viewData.setFunctionValue(FunctionNameFindId.Personalinfo_Mobile.getStringValue());
        Bundle phoneBundle = new Bundle();
        phoneBundle.putString("jumpValue", parentActivity.getPhoneNumber());
        phoneBundle.putBoolean("isEmail", false);
        phoneBundle.putString(FinalConstants.JUMP_FLAG, ChangeEmailOrPhoneFragment.class.getName());
        viewData.setBundle(phoneBundle);
        datas.add(viewData);

        viewData = new ItemViewData();
        viewData.setText(getString(R.string.option_email));
        viewData.setRightText(CommonUtil.replaceString(parentActivity.getEmailAddress(), true));
        viewData.setClassName(MoreActivity.class.getName());
        viewData.setFunctionValue(FunctionNameFindId.Personalinfo_email.getStringValue());
        Bundle emailBundle = new Bundle();
        emailBundle.putString("jumpValue", parentActivity.getEmailAddress());
        emailBundle.putBoolean("isEmail", true);
        emailBundle.putString(FinalConstants.JUMP_FLAG, ChangeEmailOrPhoneFragment.class.getName());
        viewData.setBundle(emailBundle);
        datas.add(viewData);

        if (JoinMeConstants.OWNER.equalsIgnoreCase(ApplicationUtil.getInstance().getLoginRole()) ||
                JoinMeConstants.PROXY.equalsIgnoreCase(ApplicationUtil.getInstance().getLoginRole()) ||
                JoinMeConstants.DRIVER.equalsIgnoreCase(ApplicationUtil.getInstance().getLoginRole())) {
            viewData = new ItemViewData();
            addressViewData = viewData;
            viewData.setText(getString(R.string.option_contact_address));
            String provinceKey = "";
            String provinceValue = "";
            String city = "";
            String address = "";
            String code = "";
            if (parentActivity.getContactAddress() != null) {
//                viewData.setRightText(parentActivity.getContactAddress()[0] + parentActivity.getContactAddress()[1] + parentActivity.getContactAddress()[2]);
                provinceKey = CommonUtil.isNull(parentActivity.getProvince()) ? "" : parentActivity.getProvince();
                city = CommonUtil.isNull(parentActivity.getCity()) ? "" : parentActivity.getCity();
                address = CommonUtil.isNull(parentActivity.getAddress()) ? "" : parentActivity.getAddress();
                code = CommonUtil.isNull(parentActivity.getCode()) ? "" : parentActivity.getCode();


                //根据省份的key显示相应的省份value汉字
                int provinceKeyPosition = 0;
                String[] provinceKeys = getResources().getStringArray(R.array.provinces_key);
                String[] provinceValues = getResources().getStringArray(R.array.provinces_value);
                for (int i = 0; i < provinceKeys.length; i++) {
                    if (provinceKeys[i].equals(provinceKey)) {
                        provinceKeyPosition = i;
                        break;
                    }
                }
                provinceValue = provinceValues[provinceKeyPosition];

                //显示数据
                viewData.setRightText(provinceValue + city + address);

            }
            viewData.setClassName(MoreActivity.class.getName());
//        viewData.setFunctionValue(FunctionNameFindId.Personalinfo_email.getStringValue());
            Bundle addressBundle = new Bundle();
            addressBundle.putString(FinalConstants.JUMP_FLAG, ChangeContactAddressFragment.class.getName());
            addressBundle.putString("province", provinceValue);
            addressBundle.putString("city", city);
            addressBundle.putString("address", address);
            addressBundle.putString("code", code);

            viewData.setBundle(addressBundle);
            datas.add(viewData);
        }


        //司机和代理车主应该没有此权限，不该显示此功能
        if (JoinMeConstants.OWNER.equalsIgnoreCase(ApplicationUtil.getInstance().getLoginRole())) {
            viewData = new ItemViewData();
            viewData.setText(getString(R.string.more_account_driver_license_due_date));
            viewData.setRightText(parentActivity.getLicenseExpireDate());
            datas.add(viewData);
        }


        viewData = new ItemViewData();
        viewData.setText(getString(R.string.option_change_password));
        viewData.setClassName(MoreActivity.class.getName());
        viewData.setFunctionValue(FunctionNameFindId.Personalinfo_ModifyPwd.getStringValue());
        Bundle passwordBundle = new Bundle();
        passwordBundle.putString(FinalConstants.JUMP_FLAG, ChangePasswordFragment.class.getName());
        viewData.setBundle(passwordBundle);
        datas.add(viewData);

        CustomLayoutsGroup group = new CustomLayoutsGroup(getActivity(), datas);
        group.customLineLayoutGroup(datas_layout);

        group.setOnViewItemClickListener(new CustomLayoutsGroup.OnViewItemClickListener() {
            @Override
            public boolean onViewItemClick(ItemViewData item) {
                if (item.getText().equalsIgnoreCase(getString(R.string.more_account_driver_license_due_date))) {
                    BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Personalinfo_DriLicExpDate.getStringValue());
                    showDatePicker(item.getRightText(), false);
                    return false;
                }
                return true;
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
//        if (baseActivity instanceof MoreActivity) {
//            String provinceStr = ((MoreActivity) baseActivity).getProvince();
//            String cityStr = ((MoreActivity) baseActivity).getCity();
//            String addressStr = ((MoreActivity) baseActivity).getAddress();
//            String codeStr = ((MoreActivity) baseActivity).getCode();
//            if (!TextUtils.isEmpty(provinceStr) && !TextUtils.isEmpty(cityStr) && !TextUtils.isEmpty(addressStr)) {
//                addressViewData.setRightText(provinceStr + cityStr + addressStr);
//                datas.add(addressViewData);
//            }
//        }

        if (baseActivity instanceof MoreActivity) {
            String provinceStr = ((MoreActivity) baseActivity).getProvince();
            String cityStr = ((MoreActivity) baseActivity).getCity();
            String addressStr = ((MoreActivity) baseActivity).getAddress();
            String codeStr = ((MoreActivity) baseActivity).getCode();
            if (!TextUtils.isEmpty(provinceStr) && !TextUtils.isEmpty(cityStr) && !TextUtils.isEmpty(addressStr)) {
                presenter = new AccountInfoPresenter(((MoreActivity) getActivity()).getScheduler());
                presenter.setView(this);
                presenter.start();
            }
        }
    }

    private void showDatePicker(String dateString, final boolean isBusiness) {
        SimpleDateFormat sdf = new SimpleDateFormat(FinalConstants.DATE_FORMAT);
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        try {
            Date date = sdf.parse(dateString);
            calendar.setTime(date);
        } catch (Exception e) {
            e.printStackTrace();
            calendar.setTime(new Date(System.currentTimeMillis()));
        }
        DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int montyOfYear, int dayOfMonth) {
//                StringBuilder sb = new StringBuilder();
//                sb.append(year);
//                sb.append("-");
//                sb.append(montyOfYear + 1);
//                sb.append("-");
//                sb.append(dayOfMonth);
                licenseExpireDate = year + "-" + ((montyOfYear + 1) < 10 ? 0 + (montyOfYear + 1) : (montyOfYear + 1)) + "-" + dayOfMonth;
//                licenseExpireDate = sb.toString();
                AlarmManagerUtil.notifyRenewal(getActivity(), licenseExpireDate);
                presenter.updateUserInfo(licenseExpireDate);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }


    @OnClick({R.id.portrait_rl, R.id.head_iv})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.portrait_rl:
                requestRunTimePermissions(new String[]{Manifest.permission.CAMERA}, new PermissionCall() {
                    @Override
                    public void requestSuccess() {
                        BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Personalinfo_Profile.getStringValue());//个人资料_点击头像
                        presenter.showActionSheet();
                    }

                    @Override
                    public void refused() {

                    }
                });

                break;
            case R.id.head_iv:
//                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.PersonImage.getStringValue());
                //showPortrait();
                HeadImgRes headImgRes = onstarApplication.getHeadImgRes();
                presenter.showPortrait(headImgRes);
                break;
        }
    }

    @Override
    public void showPortrait(HeadImgRes headImgRes) {
        portrait_img_rl.setVisibility(View.VISIBLE);
        bsv.setEnabled(false);

        if (headImgRes != null && !TextUtils.isEmpty(headImgRes.getFullUrl())) {
            options = OnstarApplication.getOptions(true, false, R.drawable.transparent_bg);
            imageLoader.displayImage(headImgRes.getFullUrl(), def_head_iv, options, new MyImageLoadingListener());
//            startPicutreActivity(head_iv, headImgRes.getFullUrl());
//            startPictureFragment(head_iv, headImgRes.getFullUrl());
        } else if (headImgRes == null) {
            def_head_iv.setImageResource(R.drawable.default_head);
            scaleHeadIv(def_head_iv);
        } else {
            Bitmap mBitmap = ((BitmapDrawable) head_iv.getDrawable()).getBitmap();
            if (mBitmap != null) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) def_head_iv.getLayoutParams();
                params.height = getResources().getDisplayMetrics().widthPixels;
                def_head_iv.setLayoutParams(params);
                def_head_iv.setImageBitmap(mBitmap);
                scaleHeadIv(def_head_iv);
            } else {
                def_head_iv.setImageResource(R.drawable.default_head);
                scaleHeadIv(def_head_iv);
            }
        }
        portrait_img_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                portrait_img_rl.setVisibility(View.GONE);
                bsv.setEnabled(true);
            }
        });

    }

//    private void startPicutreActivity(final View view, final String url) {
//        Picasso.with(getActivity()).load(url).fetch(new Callback() {
//            @Override
//            public void onSuccess() {
//                Intent intent = PicutureActivity.newIntent(getActivity(), url);
//                ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(
//                        getActivity(), view, PicutureActivity.TRANSIT_PIC);
//                try {
//                    ActivityCompat.startActivity(getActivity(), intent, optionsCompat.toBundle());
//                } catch (IllegalArgumentException e) {
//                    e.printStackTrace();
//                    startActivity(intent);
//                }
//            }
//
//            @Override
//            public void onError() {
//
//            }
//        });
//    }
//
//    private void startPictureFragment(View view,String url) {
//        getActivity().getSupportFragmentManager().beginTransaction()
//                .replace(com.onstar.cn.framework.R.id.fragment_container, PictureFragment.newInstance(url))
//                .addToBackStack(null)
//                .addSharedElement(view, getResources().getString(R.string.more_user_head))
//                .commit();
//    }

    class MyImageLoadingListener extends SimpleImageLoadingListener {
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (loadedImage != null) {
                final ImageView imageView = (ImageView) view;
                scaleHeadIv(imageView);
            }
        }
    }

    private void scaleHeadIv(ImageView def_head_iv) {
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(def_head_iv, "scaleX",
                0.2f, 1f);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(def_head_iv, "scaleY",
                0.2f, 1f);
        AnimatorSet animSet = new AnimatorSet();
        animSet.setInterpolator(new LinearInterpolator());
        //              animSet.setInterpolator(new DecelerateInterpolator());
        animSet.play(anim1).with(anim2);
        animSet.setDuration(300);
        animSet.start();
    }

    public void displayHeadImg(Bitmap bitmap) {
        head_iv.setImageBitmap(bitmap);
    }

    @Override
    public void setLoading(boolean isLoading) {
        progress_layout.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onResponseError(OnStarException e) {
//        AlertDialogUtil.showDialogByOnstarException(onActivity(), e);
    }

    @Override
    public void onUpdateInfoFailed(Throwable throwable) {
        if (throwable instanceof OnStarException)
            AlertDialogUtil.showDialogByOnstarException(onActivity(), (OnStarException) throwable);
    }

    @Override
    public void onReponseSuccess(Object object) {
        if (object != null) {
            if (object instanceof PersonalInfoResponse) {
                PersonalInfoResponse personalInfoResponse = (PersonalInfoResponse) object;

                parentActivity.setPhoneNumber(personalInfoResponse.getPhoneNumber());
                parentActivity.setEmailAddress(personalInfoResponse.getEmail());
                parentActivity.setLicenseExpireDate(!CommonUtil.isNull(personalInfoResponse.getLicenseExpireDate()) ? personalInfoResponse.getLicenseExpireDate() : licenseExpireDate);
                parentActivity.setContactAddress(new String[]{personalInfoResponse.getProvince(), personalInfoResponse.getCity(), personalInfoResponse.getAddress1()});
                parentActivity.setProvince(personalInfoResponse.getProvince());
                parentActivity.setCity(personalInfoResponse.getCity());
                parentActivity.setAddress(personalInfoResponse.getAddress1());
                parentActivity.setCode(personalInfoResponse.getZip());

                if (!CommonUtil.isNull(licenseExpireDate)) {
                    parentActivity.setLicenseExpireDate(licenseExpireDate);
                }
                showDatas();
            }

            if (object instanceof HeadImgRes) {
                HeadImgRes headImgRes = (HeadImgRes) object;
                onstarApplication.setHeadImgRes(headImgRes);
                imageLoader.displayImage(headImgRes.getFullUrl(), head_iv, options);
            }
        }
    }

    @Override
    public Activity onActivity() {
        return getActivity();
    }
}
